<template>
    <div class="activity-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑活动' : '添加活动' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form ref="activityFormRef" :model="formData" :rules="formRules" label-width="120px"
                    class="activity-form">

                    <!-- 语言 -->
                    <el-form-item label="语言:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                            <el-option label="中文" value="zh-CN" />
                            <el-option label="英文" value="en-US" />
                        </el-select>
                    </el-form-item>

                    <!-- 标题 -->
                    <el-form-item label="标题:" prop="title">
                        <el-input v-model="formData.title" placeholder="输入资讯标题" style="width: 300px" />
                    </el-form-item>
                    <!-- 消息类型 -->
                    <el-form-item label="消息类型:" prop="messageType">
                        <el-select v-model="formData.messageType" placeholder="请选择" style="width: 200px">
                            <el-option label="系统通知" :value="1" />
                            <el-option label="业务消息" :value="2" />
                            <el-option label="活动消息" :value="3" />
                            <el-option label="订单消息" :value="4" />
                            <el-option label="审核消息" :value="5" />
                        </el-select>
                    </el-form-item>

                    <!-- 发送者类型 -->
                    <el-form-item label="发送者类型:" prop="senderType">
                        <el-select v-model="formData.senderType" placeholder="请选择" style="width: 200px">
                            <el-option label="系统" :value="1" />
                            <el-option label="管理员" :value="2" />
                            <el-option label="机构" :value="3" />
                            <el-option label="专家" :value="4" />
                        </el-select>
                    </el-form-item>

                    <!-- 接收者类型 -->
                    <el-form-item label="接收者类型:" prop="receiverType">
                        <el-select v-model="formData.receiverType" placeholder="请选择" style="width: 200px">
                            <el-option label="全部用户" :value="1" />
                            <el-option label="指定用户" :value="2" />
                            <el-option label="指定机构" :value="3" />
                            <el-option label="指定专家" :value="4" />
                        </el-select>
                    </el-form-item>

                    <!-- 点击数 -->
                    <el-form-item label="点击数:" prop="clickCount">
                        <el-input-number v-model="formData.clickCount" :min="0" :max="999999" controls-position="right"
                            style="width: 200px" />
                    </el-form-item>

                    <!-- 内容 -->
                    <el-form-item label="内容:" prop="content">
                        <el-input v-model="formData.content" type="textarea" :rows="8" placeholder="请输入内容"
                            style="width: 100%" />
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmit">保存</el-button>
                        <el-button @click="handleCancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, Plus } from '@element-plus/icons-vue';
import { MessageRequest } from '@/types/message';
import { createMessage, updateMessage, getMessageDetail } from '@/api/system/message';

const route = useRoute();
const router = useRouter();

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id);

// 表单引用
const activityFormRef = ref();


// 表单数据
const formData = reactive({
    messageType: 3, // 默认活动消息
    senderType: 1, // 默认系统
    receiverType: 1, // 默认全部用户
    language: 'zh-CN',
    title: '',
    content: '',
    clickCount: 0,
    receiverIds: [] as string[]
});



// 表单验证规则
const formRules = {
    messageType: [
        { required: true, message: '请选择消息类型', trigger: 'change' }
    ],
    senderType: [
        { required: true, message: '请选择发送者类型', trigger: 'change' }
    ],
    receiverType: [
        { required: true, message: '请选择接收者类型', trigger: 'change' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 50, message: '标题长度在2-50个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' }
    ]
};



// 提交表单
const handleSubmit = async () => {
    try {
        await activityFormRef.value.validate();

        const messageData: MessageRequest = {
            messageType: formData.messageType,
            title: formData.title,
            content: formData.content,
            clickCount: formData.clickCount,
            senderType: formData.senderType,
            receiverType: formData.receiverType,
            receiverIds: formData.receiverIds,
            language: formData.language
        };

        if (isEdit.value) {
            // 编辑模式
            messageData.id = route.params.id as string;
            const res = await updateMessage(route.params.id as string, messageData);
            const responseData = res as any;

            if (responseData && responseData.code === 200) {
                ElMessage.success('编辑成功');
                router.push('/activity-list');
            } else {
                const errorMsg = (responseData && responseData.msg) || '编辑失败';
                ElMessage.error(errorMsg);
            }
        } else {
            // 新增模式
            const res = await createMessage(messageData);
            const responseData = res as any;

            if (responseData && responseData.code === 200) {
                ElMessage.success('新增成功');
                router.push('/activity-list');
            } else {
                const errorMsg = (responseData && responseData.msg) || '新增失败';
                ElMessage.error(errorMsg);
            }
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('操作失败，请稍后重试');
    }
};

// 取消操作
const handleCancel = () => {
    ElMessageBox.confirm(
        '确定要离开吗？未保存的内容将丢失。',
        '确认离开',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        router.go(-1);
    }).catch(() => {
        // 用户取消
    });
};

// 加载消息详情
const loadMessageDetail = async (id: string) => {
    try {
        const res = await getMessageDetail(id);
        const responseData = res as any;

        if (responseData && responseData.code === 200 && responseData.data) {
            const data = responseData.data;
            formData.messageType = data.messageType;
            formData.senderType = data.senderType;
            formData.receiverType = data.receiverType;
            formData.language = data.language;
            formData.title = data.title;
            formData.content = data.content;
            formData.clickCount = data.clickCount || 0;
            formData.receiverIds = data.receiverIds ? JSON.parse(data.receiverIds) : [];
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取消息详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取消息详情失败:', error);
        ElMessage.error('获取消息详情失败，请稍后重试');
    }
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式，加载数据
        const id = route.params.id as string;
        loadMessageDetail(id);
    }
});

</script>

<style scoped>
.activity-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 表单内容 */
.form-card {
    border-radius: 8px;
}

.activity-form {
    padding: 20px;
}

.form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}



/* 响应式设计 */
@media (max-width: 768px) {
    .activity-form-container {
        padding: 10px;
    }

    .activity-form {
        padding: 15px;
    }
}
</style>
